package com.slipper.system.login;

import com.slipper.common.bo.Result;
import com.slipper.common.util.*;
import com.slipper.sfts.api.member.bo.MemberBO;
import com.slipper.sfts.api.member.service.IMemberSv;
import com.slipper.system.api.log.bo.LoginLogBO;
import com.slipper.system.common.Constants;
import com.slipper.system.common.UserDetail;
import com.slipper.system.log.LogAsyncService;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
public class LoginController {
    @Resource
    private IMemberSv memberSv;
    @Resource
    private LogAsyncService logAsyncService;

    @PostMapping("/login")
    public String login(HttpServletRequest request, @RequestBody MemberBO bo) throws Exception {
        String captcha = Constants.getAndCleanCaptcha();
        if (captcha != null && (bo.getCaptcha() == null || "".equals(bo.getCaptcha())
                || !bo.getCaptcha().equalsIgnoreCase(captcha))) {
            return ResultUtil.toErrorJson("验证码不正确！");
        }

        if (StringUtil.isBlank(bo.getUsername())) {
            return ResultUtil.toErrorJson("用户名不能为空！");
        }

        Result<MemberBO> memberResult = this.memberSv.queryByLogin(bo);
        if (!memberResult.isSuccess() || memberResult.getData() == null) {
            return ResultUtil.toErrorJson("用户名错误！");
        }

        bo.setPassword(RSAUtil.decrypt(bo.getPassword(), Constants.getRSAKey().getPrivateKey()));
        MemberBO member = memberResult.getData();
        if (!MD5.encode(bo.getPassword()).equals(member.getPassword())) {
            return ResultUtil.toErrorJson("密码错误！");
        }
        if (MemberBO.APPROVE_STATUS_PENDING.equals(member.getApproveStatus())) {
            return ResultUtil.toErrorJson("账号审核中，请稍候...");
        }
        if (MemberBO.APPROVE_STATUS_NOT_PASS.equals(member.getApproveStatus())) {
            String result = StringUtil.isBlank(member.getApproveResult())
                    ? "。" : "，原因：" + member.getApproveResult();
            return ResultUtil.toErrorJson("账号审核未通过" + result);
        }

        UserDetail userDetail = new UserDetail();
        userDetail.setMember(member);

        LoginLogBO loginLog = new LoginLogBO();
        loginLog.setUserId(member.getId());
        loginLog.setUserName(member.getUsername());
        loginLog.setLoginTime(new Date());
        loginLog.setIpAddress(Tool.getIpAddr(request));
        loginLog.setBrowerInfo(request.getHeader("User-Agent"));
        loginLog.setLoginType("浏览器登录");
        loginLog.setOperateInfo("登录成功！");
        this.logAsyncService.saveLoginLog(loginLog);

        member.setToken(Tool.getUUID());
        Constants.setCurrentUser(userDetail);

        return ResultUtil.toJson(member);
    }

    @PostMapping("/register")
    public String register(@RequestBody MemberBO bo) throws Exception {
        if (StringUtil.isBlank(bo.getUsername())) {
            return ResultUtil.toErrorJson("用户名不能为空！");
        }
        if (StringUtil.isBlank(bo.getPassword())) {
            return ResultUtil.toErrorJson("密码不能为空！");
        }
        String captcha = Constants.getAndCleanCaptcha();
        if (captcha != null && (bo.getCaptcha() == null || "".equals(bo.getCaptcha())
                || !bo.getCaptcha().equalsIgnoreCase(captcha))) {
            return ResultUtil.toErrorJson("验证码不正确！");
        }

        bo.setPassword(RSAUtil.decrypt(bo.getPassword(), Constants.getRSAKey().getPrivateKey()));
        return ResultUtil.toJson(memberSv.register(bo));
    }

    @PostMapping("/loginSalt")
    public String loginSalt() {
        return ResultUtil.toJson(Constants.getRSAKey().getPublicKey());
    }

    @PostMapping("/loginInfo")
    public String loginInfo() {
        return ResultUtil.toJson(Constants.getCurrentUser().getMember());
    }

    @PostMapping("/logoutUser")
    public String logoutUser(HttpServletRequest request) {
        UserDetail userDetail = Constants.getCurrentUser();
        LoginLogBO loginLog = new LoginLogBO();
        loginLog.setUserId(userDetail.getMember().getId());
        loginLog.setUserName(userDetail.getMember().getUsername());
        loginLog.setLoginTime(new Date());
        loginLog.setIpAddress(Tool.getIpAddr(request));
        loginLog.setLoginType("浏览器登录");
        loginLog.setBrowerInfo(request.getHeader("User-Agent"));
        loginLog.setOperateInfo("退出登录！");
        this.logAsyncService.saveLoginLog(loginLog);

        Constants.getCurrentRequest().getSession().invalidate();
        return ResultUtil.toSuccessJson("退出登录成功！");
    }
}
